package com.ruge.system.service.impl;

import com.ruge.common.util.GsonUtil;
import com.ruge.common.util.Constants;
import com.ruge.common.util.ShiroUtil;
import com.ruge.system.pojo.entity.SysRole;
import com.ruge.system.pojo.entity.SysUser;
import com.ruge.system.pojo.entity.SysUserRole;
import com.ruge.system.repository.SysUserRepository;
import com.ruge.system.repository.SysUserRoleRepository;
import com.ruge.system.pojo.request.UserRequest;
import com.ruge.system.service.SysUserService;
import com.ruge.system.pojo.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2020-03-05  20:38
 * 描述 ：
 *
 * @author dell
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserRepository sysUserRepository;
    @Resource
    private SysUserRoleRepository sysUserRoleRepository;

    /**
     * 通过登录用户名 查询用户对象
     *
     * @param loginName 登录用户名
     * @return
     */
    @Override
    public SysUser findByLoginName(String loginName) {
        return sysUserRepository.findByLoginName(loginName);
    }

    /**
     * 查询接口
     *
     * @param model 用户请求model
     * @return 返回数据对象
     */
    @Override
    public Page<UserVo> findAll(UserRequest model) {
        Specification<SysUser> specification = (root, query, cb) -> {
            /**
             * 获取条件对象
             */
            Predicate conjunction = cb.conjunction();
            if (model != null) {
                if (StringUtils.isNotBlank(model.getLoginName())) {
                    conjunction.getExpressions().add(cb.like(root.get("loginName"), "%" + model.getLoginName() + "%"));
                }
                if (StringUtils.isNotBlank(model.getNickName())) {
                    conjunction.getExpressions().add(cb.like(root.get("nickName"), "%" + model.getNickName() + "%"));
                }
                if (StringUtils.isNotBlank(model.getPhone())) {
                    conjunction.getExpressions().add(cb.like(root.get("phone"), "%" + model.getPhone() + "%"));
                }
            }
            return conjunction;
        };
        Sort sort = Sort.by(Sort.Order.desc("id"));
        Pageable pageable = PageRequest.of(model != null ? model.getPage() : 0, model != null ? model.getLimit() : 15, sort);
        Page<SysUser> page = sysUserRepository.findAll(specification, pageable);
        return new PageImpl<>(GsonUtil.GsonToListVo(page.getContent(), UserVo.class), pageable, page.getTotalElements());
    }


    /**
     * 保存接口
     *
     * @param sysUser
     * @return
     */
    @Override
    public SysUser save(SysUser sysUser) {
        return sysUserRepository.save(sysUser);
    }

    /**
     * 数据删除接口
     *
     * @param id
     * @return
     */
    @Override
    public void deleteById(Long id) {
        sysUserRepository.deleteById(id);
    }

    /**
     * 批量操作
     *
     * @param map
     * @return
     */
    @Override
    public List<SysUser> batch(Map<String, List<SysUser>> map) {
        return sysUserRepository.batch(map);
    }

    /**
     * 给用户进行角色授权
     *
     * @param list
     * @return
     */
    @Override
    public void authRole(List<UserRequest> list) {
        sysUserRoleRepository.deleteAllBySysUser_Id(list.get(0).getUid());
        list.forEach(e -> {
            SysUserRole userRole = new SysUserRole();
            SysUser user = new SysUser();
            SysRole role = new SysRole();
            user.setId(e.getUid());
            role.setId(e.getRid());
            userRole.setSysUser(user);
            userRole.setSysRole(role);
            sysUserRoleRepository.save(userRole);
        });
    }

    /**
     * 用户密码重置
     *
     * @param entity
     */
    @Override
    public void resetPwd(UserRequest entity) {
        SysUser user = new SysUser();
        user.setId(entity.getId());
        user.setPassword(Constants.DEFAULT_PASSWORD);
        sysUserRepository.save(user);
    }

    /**
     * 用户修改密码
     *
     * @param request
     * @return
     */
    @Override
    public String updatePwd(UserRequest request) {
        Boolean flagOld = StringUtils.isNotBlank(request.getOldPassword());
        Boolean flagNew = StringUtils.equals(request.getNewPassword(), request.getAgainPassword());
        Long userId = ShiroUtil.getActiveUser().getUser().getId();
        Optional<SysUser> optionalSysUser = sysUserRepository.findById(userId);
        if (optionalSysUser.isPresent()){
            SysUser sysUser = optionalSysUser.get();
            if (!StringUtils.equals(request.getOldPassword(),sysUser.getPassword())){
                return "原密码错误";
            }
            if (!flagNew) {
                return "两次密码不一致 请重新输入";
            }
            if (flagOld) {
                sysUser.setPassword(request.getNewPassword());
            }
            sysUserRepository.save(sysUser);
        }

        return "密码修改成功";
    }
}
